// 作为服务端
#include "UdpServer.hpp"
#include <memory>
#include <stdlib.h>
#include <cstdio>

void Usage(string proc)
{
    cout << "\n\rUsage: " << proc << " port[1024+]\n" << endl;
}

string ExcuteCommand(const string& cmd)
{
    FILE* fp = popen(cmd.c_str(), "r");
    if(fp == nullptr)
    {
        perror("popen");
        return "error";
    }
    string result;
    char buffer[4096];
    while(true)
    {
        char* tmp = fgets(buffer, sizeof(buffer), fp);
        if(tmp == nullptr) break;
        result += buffer;
    }
    pclose(fp);
    return result;
}

string Handler(const string& str)
{
    string res = "Server get a message: ";
    res += str;
    cout << res << endl;

    return res;
}

// ./udpserver port 才可运行服务器
int main(int argc, char* argv[])
{
    if(argc != 2)
    {
        Usage(argv[0]);
        exit(0);
    }

    uint16_t port = stoi(argv[1]);
    unique_ptr<UdpServer> svr(new UdpServer());
    svr->Init();
    svr->Run(ExcuteCommand);

    return 0;
}